import {ref, reactive} from "vue";

export const useFile = () => {
    let baseUrl = import.meta.env.VITE_FILE_BASE_PATH;
    let srcList = ref([])
    let showViewer = ref(false)
    let fileList = ref([])
    let action = import.meta.env.VITE_FILE_BASE_PATH + '/api/project/upload'
    let headers = {
        Token: JSON.parse(sessionStorage.getItem('userInfo')).token
    }

    const handlePreview = (file) => {
        console.log('file', file);
        let index = file.name.lastIndexOf('.')
        if (!file.url && file.response) {
            file.url = file.response.data.path
        }
        let type = file.name.substr(index + 1) //获取文件后缀名
        if (type === 'png' || type === 'jpg' || type === 'jpeg' || type === 'PNG' || type === 'JPG' || type === 'JPEG') {
            srcList.value = [file.url]
            showViewer.value = true
        } else {
            const iframe = document.createElement('iframe')
            iframe.style.display = 'none'       // 防止影响页面
            iframe.style.height = 0             // 防止影响页面
            iframe.src = baseUrl + '/api/index/down?file=' + file.url
            console.log(iframe.src);
            document.body.appendChild(iframe)   // 这一行必须，iframe挂在到dom树上才会发请求
            // 5分钟之后删除（onload方法对于下载链接不起作用，就先抠脚一下吧）
            setTimeout(() => {
                iframe.remove()
            }, 5 * 60 * 1000)
        }
    }

    return {
        handlePreview,
        action,
        srcList,
        showViewer,
        headers,
        fileList
    }
}